package com.chance.cc.crawler.prod.command;

import com.chance.cc.crawler.core.downloader.Downloader;
import com.chance.cc.crawler.core.downloader.HttpConfig;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.downloader.http.HttpClientDownloader;
import com.chance.cc.crawler.core.downloader.http.HttpClientGenerator;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

/**
 * created by CC on 2020/11/24
 * mail 279020185@qq.com
 */
public abstract class HttpCommand implements Command<HttpRequest, HttpPage>{

    @Getter
    @Setter
    private String host;

    @Getter
    @Setter
    private int port;

    @Getter
    @Setter
    private Downloader downloader;

    @Getter
    @Setter
    private HttpConfig httpConfig;

    private String urlPrefix;

    public HttpCommand(String host,int port){
        this(host,port,HttpConfig.me("command"));
    }

    public HttpCommand(String host,int port,HttpConfig httpConfig){
        this.host = host;
        this.port = port;
        this.httpConfig = httpConfig;
        HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
        httpClientDownloader.setClientGenerator(new HttpClientGenerator());
        this.downloader = httpClientDownloader;
        this.urlPrefix = initUrlPrefix(host,port);
    }

    public HttpPage doCommand(HttpRequest input) {
        return this.downloader.download(input,this.httpConfig);
    }

    public String commandUrl(String path){
        return StringUtils.joinWith("/",this.urlPrefix,path);
    }

    public abstract String initUrlPrefix(String host,int port);
}
